import router from '@/router/index'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import '@/utils/memoryToken'

// 白名单
const whiteList = ['/login', '/h5'] // '/404'

//使下文的next()方法慢于组件的生命周期
function fn() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('OK')
    }, 100)
  })
}
// 路由守卫
router.beforeEach(async (to, from, next) => {
  setToken('test-token')
  if (getToken()) {
    console.log(123)
    if (to.path === '/login') {
      removeToken()
    }
    next()
  } else {
    if (to.path.includes('/h5') || whiteList.indexOf(to.path) !== -1) {
      if (to.path === '/login') {
        removeToken()
      }
      next()
    } else {
      await fn()
      if (getToken()) {
        next(to.fullPath)
      } else {
        next(`/login`)
      }
    }
  }
})